<template>
  <div class="department-management-container">
    <!-- 操作按钮区域 -->
    <action-buttons
      :buttons="buttonsConfig"
      :selected-data="selectedRows"
      :no-confirm-buttons="['log', 'export']"
      @add="handleAdd"
      @delete="handleDelete"
      @export="handleExport"
      @log="handleLog"
    />
    
    <!-- 表格区域 -->
    <custom-table
      :data="tableData"
      :columns="tableColumns"
      :loading="tableLoading"
      :current-page="pagination.currentPage"
      :page-size="pagination.pageSize"
      :total="pagination.total"
      table-id="department-table"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <!-- 展开行图标 -->
      <template #expandIcon="{ row }">
        <span class="expand-icon">
          <el-icon v-if="row.children && row.children.length">
            <arrow-right />
          </el-icon>
        </span>
      </template>
      
      <!-- 操作列 -->
      <template #operation="{ row }">
        <theme-button v-if="tablePermissions.edit" link @click="handleEdit(row)">编辑</theme-button>
      </template>
    </custom-table>
    
    <!-- 部门信息对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      class="department-dialog"
    >
      <el-form
        ref="formRef"
        :model="formModel"
        :rules="formRules"
        label-width="100px"
        class="base-form"
      >
        <div class="form-row form-row-horizontal">
          <el-form-item label="部门编码" prop="code" required class="form-item-half">
            <el-input
              v-model="formModel.code"
              placeholder="请输入部门编码"
              maxlength="20"
            />
          </el-form-item>
          
          <el-form-item label="部门名称" prop="name" required class="form-item-half">
            <el-input
              v-model="formModel.name"
              placeholder="请输入部门名称"
              maxlength="50"
            />
          </el-form-item>
        </div>
        
        <div class="form-row form-row-horizontal">
          <el-form-item label="部门简称" prop="shortName" class="form-item-half">
            <el-input
              v-model="formModel.shortName"
              placeholder="请输入部门简称"
              maxlength="20"
            />
          </el-form-item>
          
          <el-form-item label="上级部门" prop="parentId" required class="form-item-half">
            <el-select
              v-model="formModel.parentId"
              placeholder="请选择上级部门"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in departmentTreeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </div>
        
        <div class="form-row form-row-horizontal">
          <el-form-item label="所属公司" prop="companyId" required class="form-item-half">
            <el-select
              v-model="formModel.companyId"
              placeholder="请选择所属公司"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in companyOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="联系人" prop="contactPerson" class="form-item-half">
            <el-input
              v-model="formModel.contactPerson"
              placeholder="请输入联系人"
              maxlength="20"
            />
          </el-form-item>
        </div>
        
        <div class="form-row form-row-horizontal">
          <el-form-item label="联系电话" prop="contactPhone" class="form-item-half">
            <el-input
              v-model="formModel.contactPhone"
              placeholder="请输入联系电话"
              maxlength="20"
            />
          </el-form-item>
        </div>
        
        <div class="form-row">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formModel.remark"
              type="textarea"
              placeholder="请输入备注"
              maxlength="200"
              :rows="3"
            />
          </el-form-item>
        </div>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 日志弹窗 -->
    <log-dialog
      v-model:visible="logDialogVisible"
      :log-data="logData"
      :total="logPagination.total"
      :current-page="logPagination.currentPage"
      :page-size="logPagination.pageSize"
      @size-change="handleLogSizeChange"
      @current-change="handleLogCurrentChange"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowRight } from '@element-plus/icons-vue'

// 表格列配置
const tableColumns = [
  { prop: 'name', label: '部门名称', minWidth: 120 },
  { prop: 'shortName', label: '部门简称', minWidth: 100 },
  { prop: 'code', label: '部门编码', minWidth: 100 },
  { prop: 'parentDept', label: '上级部门', minWidth: 120 },
  { prop: 'company', label: '所属公司', minWidth: 120 },
  { prop: 'contactPerson', label: '联系人', minWidth: 100 },
  { prop: 'contactPhone', label: '联系电话', minWidth: 120 },
  { prop: 'createTime', label: '操作时间', minWidth: 160 },
  { prop: 'operator', label: '操作人', minWidth: 100 },
  { prop: 'operation', label: '操作', minWidth: 100, fixed: 'right' }
]

// 操作按钮配置
const buttonsConfig = ref({
  add: { visible: true, order: 1, type: 'primary' },
  delete: { visible: true, order: 2 },
})

// 表格操作权限
const tablePermissions = ref({
  edit: true
})

// 表格数据相关
const tableData = ref([])
const tableLoading = ref(false)
const selectedRows = ref([])

// 分页相关
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  page: 1,
  size: 10
})

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增部门')
const formRef = ref(null)
const formModel = reactive({
  id: '',
  name: '',
  shortName: '',
  code: '',
  parentId: '',
  companyId: '',
  contactPerson: '',
  contactPhone: '',
  remark: ''
})

// 表单校验规则
const formRules = {
  code: [
    { required: true, message: '请输入部门编码', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' }
  ],
  shortName: [
    { required: false, message: '请输入部门简称', trigger: 'blur' }
  ],
  parentId: [
    { required: true, message: '请选择上级部门', trigger: 'change' }
  ],
  companyId: [
    { required: true, message: '请选择所属公司', trigger: 'change' }
  ],
  contactPerson: [
    { required: false, message: '请输入联系人', trigger: 'blur' }
  ],
  contactPhone: [
    { required: false, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 日志弹窗相关
const logDialogVisible = ref(false)
const logData = ref([])
const logPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 加载状态
const loading = ref(false)

// 公司选项数据
const companyOptions = ref([])

// 部门树选项
const departmentTreeOptions = ref([])

// 获取表格数据
const fetchTableData = async () => {
  tableLoading.value = true
  try {
    // 模拟异步请求
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟数据
    tableData.value = [
      {
        id: '1',
        name: '技术部',
        shortName: '技术',
        code: 'TECH001',
        parentDept: '总部',
        company: '测试公司',
        contactPerson: '张三',
        contactPhone: '13800138000',
        createTime: '2023-01-01 12:00:00',
        operator: 'admin'
      },
      {
        id: '2',
        name: '市场部',
        shortName: '市场',
        code: 'MKT001',
        parentDept: '总部',
        company: '测试公司',
        contactPerson: '李四',
        contactPhone: '13900139000',
        createTime: '2023-01-02 12:00:00',
        operator: 'admin'
      }
    ]
    
    // 设置总数
    pagination.total = 100
  } catch (error) {
    console.error('获取数据失败', error)
    ElMessage.error('获取数据失败')
  } finally {
    tableLoading.value = false
  }
}

// 选择行变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 处理分页变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchTableData()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchTableData()
}

// 添加部门
const handleAdd = () => {
  // 重置表单
  Object.keys(formModel).forEach(key => {
    formModel[key] = ''
  })
  
  dialogTitle.value = '新增部门'
  dialogVisible.value = true
}

// 编辑部门
const handleEdit = (row) => {
  // 填充表单
  Object.keys(formModel).forEach(key => {
    if (key in row) {
      formModel[key] = row[key]
    }
  })
  
  dialogTitle.value = '编辑部门'
  dialogVisible.value = true
}

// 删除部门
const handleDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的数据')
    return
  }
  
  ElMessageBox.confirm('确定要删除选中的部门吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 执行删除操作
    ElMessage.success('删除成功')
    fetchTableData()
  }).catch(() => {
    // 取消删除
  })
}

// 导出
const handleExport = () => {
  ElMessage.success('导出成功')
}

// 查看日志
const handleLog = () => {
  // 模拟日志数据
  logData.value = [
    {
      id: '1',
      operateType: '新增',
      content: '新增部门: A部门',
      operateTime: '2024-11-02 12:00:00',
      operator: '小李'
    },
    {
      id: '2',
      operateType: '修改',
      content: '修改部门: B部门',
      operateTime: '2024-11-01 22:00:00',
      operator: '小李'
    }
  ]
  
  logPagination.total = logData.value.length
  logDialogVisible.value = true
}

// 日志分页大小变化
const handleLogSizeChange = (size) => {
  logPagination.pageSize = size
  // 获取日志数据
}

// 日志页码变化
const handleLogCurrentChange = (page) => {
  logPagination.currentPage = page
  // 获取日志数据
}

// 提交表单
const handleConfirm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid, fields) => {
    if (valid) {
      // 这里添加提交逻辑
      console.log('提交表单', formModel)
      ElMessage.success(formModel.id ? '修改成功' : '添加成功')
      dialogVisible.value = false
      fetchTableData()
    } else {
      console.log('表单校验失败', fields)
      return false
    }
  })
}

// 获取公司列表
const fetchCompanyOptions = async () => {
  try {
    loading.value = true
    // TODO: 替换为实际的API调用
    // const { data } = await api.getCompanyList()
    // 模拟数据
    const data = [
      { id: '1', name: '公司A' },
      { id: '2', name: '公司B' },
      { id: '3', name: '公司C' }
    ]
    companyOptions.value = data
  } catch (error) {
    console.error('获取公司列表失败', error)
    ElMessage.error('获取公司列表失败')
  } finally {
    loading.value = false
  }
}

// 获取部门树
const fetchDepartmentTree = async () => {
  try {
    loading.value = true
    // TODO: 替换为实际的API调用
    // const { data } = await api.getDepartmentTree()
    // 模拟数据
    const data = [
      { 
        id: '1', 
        name: '总部', 
        children: [
          { id: '11', name: '技术部' },
          { id: '12', name: '市场部' }
        ]
      },
      { 
        id: '2', 
        name: '分公司', 
        children: [
          { id: '21', name: '销售部' }
        ]
      }
    ]
    departmentTreeOptions.value = data
  } catch (error) {
    console.error('获取部门树失败', error)
    ElMessage.error('获取部门树失败')
  } finally {
    loading.value = false
  }
}

// 初始化数据
onMounted(() => {
  fetchTableData()
  fetchCompanyOptions()
  fetchDepartmentTree()
})
</script>

<style lang="scss" scoped>
.department-management-container {
  .base-form {
    .form-row {
      margin-bottom: 18px;
      
      &.form-row-horizontal {
        display: flex;
        gap: 20px;
        
        .form-item-half {
          flex: 1;
          min-width: 0;
        }
      }
      
      .el-form-item {
        margin-bottom: 0;
        
        :deep(.el-form-item__label) {
          font-size: 14px;
          line-height: 32px;
          color: #333;
          padding-right: 12px;
          
          &::before {
            color: #f56c6c;
          }
        }
        
        :deep(.el-input__wrapper),
        :deep(.el-textarea__inner),
        :deep(.el-select .el-input__wrapper) {
          box-shadow: 0 0 0 1px #dcdfe6 inset;
          border-radius: 0;
          
          &:hover {
            box-shadow: 0 0 0 1px #c0c4cc inset;
          }
          
          &.is-focus {
            box-shadow: 0 0 0 1px #409eff inset;
          }
        }
        
        :deep(.el-select) {
          width: 100%;
        }
      }
    }
  }
  
  .dialog-footer {
    display: flex;
    justify-content: center;
    
  }
  
  .expand-icon {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 16px;
    height: 16px;
  }
}

/* 弹窗样式 */
:deep(.department-dialog) {
  border-radius: 2px;
  
  .el-dialog__header {
    margin: 0;
    border-bottom: 1px solid #e4e7ed;
    padding: 16px 24px;
    
    .el-dialog__title {
      font-size: 16px;
      font-weight: 500;
      color: #333;
    }
  }
  
  .el-dialog__headerbtn {
    top: 16px;
    right: 20px;
  }
  
  .el-dialog__body {
    padding: 24px;
  }
  
  .el-dialog__footer {
    padding: 16px 24px;
  }
}
</style> 